from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import logging

#初始化本地drirver
def new_driver(headless=True):
    #PROXY="http://backtracker.asuscomm.com:4128"
    chrome_options = webdriver.ChromeOptions()
    if headless:
        chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--start-maximized')
    chrome_options.add_argument('--disable-infobars')
    chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
    #chrome_options.add_argument('--proxy-server=http://backtracker.asuscomm.com:4128')
    #chrome_options.add_argument('--proxy-server=%s' % PROXY)
    #chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
    driver = webdriver.Chrome(options=chrome_options)
    driver.implicitly_wait(30)
    return driver

#初始化远程driver
def new_remote_driver():
    driver = webdriver.Remote(
        command_executor="http://39.98.224.108:24444/wd/hub",
        desired_capabilities=DesiredCapabilities.CHROME
    )
    driver.implicitly_wait(30)
    return driver

#解决重复日志的问题
loggers = {}
def get_logger(name):
    global loggers

    if loggers.get(name):
        return loggers.get(name)
    else:
        logger = logging.getLogger(name)
        logger.setLevel(logging.INFO)
        handler = logging.FileHandler('../../logs/'+name+'.log')
        formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        loggers[name] = logger
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        logger.addHandler(console)

        return logger
